from threading import *
import wx
from Carry import EVT_RESULT,ResultEvent
from socket import *

# Thread class que executa o processo de obter os portos abertos
class PortScanThread(Thread):
    """Worker Thread Class."""
    def __init__(self, notify_window,hostname,limit):
        """Init Worker Thread Class."""
        Thread.__init__(self)
        self._notify_window = notify_window
        self.hostname = hostname
        self.limit = limit
        self.start()

    def run(self):
        """Run Worker Thread."""
        ports = self.portscan(self.hostname,self.limit,3)
        wx.PostEvent(self._notify_window, ResultEvent({'type':3,'ports':ports}))

    def portscan(self,ip,limit,timeout):
    	"""Funcao responsavel por identificar os portos abertos"""
        openports = []
        for n in range(0,limit):
            s = socket(AF_INET, SOCK_STREAM)
            s.settimeout(timeout) #timeout pre-definido de 3 segundos
            try:
                if s.connect_ex((ip, n))==0: # o porto esta no estado aberto (0)
                    openports.append(n)
            except:
                pass
            s.close()
        return openports